package com.youlu.campus.web.cms.service.impl;

import com.alibaba.fastjson.JSON;
import com.mongodb.client.result.UpdateResult;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.web.cms.entity.*;
import com.youlu.campus.web.common.CmsErrorCode;
import com.youlu.campus.web.cms.service.ComplaintInfoService;
import com.youlu.campus.web.cms.vo.ComplaintInfoQueryRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ComplaintInfoServiceImpl implements ComplaintInfoService {
    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Page<ComplaintInfo> query(ComplaintInfoQueryRequest req) {
        logger.info(":>>> 开始获取投诉列表:{}", JSON.toJSONString(req));
        if (Objects.isNull(req)) {
            logger.error(":>>> 参数错误");
            throw new BusinessException(CmsErrorCode.PARAM_ERROR.getMessage());
        }
        Query query = new Query();
//        query.addCriteria(Criteria.where("tenantId").is(req.getTenantId()));
        if (Objects.nonNull(req.getType()))
            query.addCriteria(Criteria.where("type").is(req.getType()));

        if (StringUtils.isNotBlank(req.getContent())) {
            Pattern pattern = Pattern.compile("^.*" + req.getContent() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("content").regex(pattern));
        }
        long count = mongoTemplate.count(query, ComplaintInfo.class);
        PageRequest pageRequest = PageRequest.of(req.getPage() - 1, req.getPageSize());
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ComplaintInfo> datas = mongoTemplate.find(query.with(pageRequest), ComplaintInfo.class);
        return PageableExecutionUtils.getPage(datas, pageRequest, () -> count);
    }

    @Override
    public boolean setBlackList(String id, String userId, String status) {
        logger.info(":>>> 开始设置用户:{} 黑名单", userId);
        if (StringUtils.isBlank(userId) || Objects.isNull(status)) {
            logger.error(":>>> 参数错误");
            throw new BusinessException(CmsErrorCode.PARAM_ERROR.getMessage());
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(userId));
        boolean exist = mongoTemplate.exists(query, VisitorUser.class);
        if (!exist) {
            logger.error(":>>> 用户:{} 不存在", userId);
            throw new BusinessException(CmsErrorCode.DATA_NOT_EXIST.getMessage());
        }
        Update update = new Update();
        update.set("status", status);
        update.set("updatedTime", new Date());
        UpdateResult result = mongoTemplate.updateFirst(query, update, VisitorUser.class);
        logger.info(":>>> 修改用户黑名单结果:{}", result.getModifiedCount() > 0 ? true : false);


        Query query1 = new Query();
        query1.addCriteria(Criteria.where("id").is(id));
        Update update1 = new Update();
        update1.set("complaintedUserStatus", status);
        update1.set("updatedTime", new Date());
        mongoTemplate.updateFirst(query1, update1, ComplaintInfo.class);
        return result.getModifiedCount() > 0 ? true : false;

    }

    @Override
    public boolean updateContentStatus(String contentId, Integer type, Integer status) {
        logger.info(":>>> 开始更新打卡显示状态 with contentId:{},type:{},status:{}", contentId, type, status);
        if (StringUtils.isBlank(contentId) || Objects.isNull(type) || Objects.isNull(status)) {
            logger.error(":>>> 参数错误");
            throw new BusinessException(CmsErrorCode.PARAM_ERROR.getMessage());
        }
        /**
         * 类型,0:动态,1:打卡
         */
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(contentId));
        switch (type) {
            case 0:
                boolean exist = mongoTemplate.exists(query, CommunityContent.class);
                if (!exist) {
                    logger.error(":>>> 打卡动态:{} 不存在", contentId);
                    throw new BusinessException(CmsErrorCode.DATA_NOT_EXIST.getMessage());
                }
                Update update = new Update();
                update.set("displayed", Boolean.FALSE);
                mongoTemplate.updateFirst(query, update, CommunityContent.class);
                return true;
            case 1:
                boolean exist1 = mongoTemplate.exists(query, CheckInInfo.class);
                if (!exist1) {
                    logger.error(":>>> 打卡信息:{} 不存在", contentId);
                    throw new BusinessException(CmsErrorCode.DATA_NOT_EXIST.getMessage());
                }
                Update update1 = new Update();
                update1.set("displayed", Boolean.FALSE);
                mongoTemplate.updateFirst(query, update1, CheckInInfo.class);
                return true;
            default:
                logger.error(":>>> 修改投诉状态错误,类型错误:{}", type);
                return true;
        }

    }

    @Override
    public boolean create(String tenantId, ComplaintInfo c) {
        log.info(":>>> 开始创建举报接口:{},{}", tenantId, JSON.toJSONString(c));
        if (Objects.isNull(c) || Objects.isNull(c.getType()) || Objects.isNull(c.getContentId()) ||
                Objects.isNull(c.getContent()) ||
                Objects.isNull(c.getComplaintedUserId()) || Objects.isNull(c.getComplaintUserId())) {
            logger.error(":>>> 新增举报接口参数错误");
            throw new BusinessException(CmsErrorCode.PARAM_ERROR.getMessage());
        }
        Query query = new Query().addCriteria(Criteria.where("id").is(c.getComplaintUserId()));
        VisitorUser complaintUser = mongoTemplate.findOne(query, VisitorUser.class);
        if (Objects.isNull(complaintUser)) {
            log.error(":>>> 举报用户:{} 不存在", c.getComplaintUserId());
            throw new BusinessException(CmsErrorCode.DATA_NOT_EXIST.getMessage());
        }
        Query query1 = new Query().addCriteria(Criteria.where("id").is(c.getComplaintedUserId()));
        VisitorUser complaintedUser = mongoTemplate.findOne(query1, VisitorUser.class);
        if (Objects.isNull(complaintedUser)) {
            log.error(":>>>  被举报用户:{} 不存在", c.getComplaintedUserId());
            throw new BusinessException(CmsErrorCode.DATA_NOT_EXIST.getMessage());
        }
        c.setComplaintUserNickName(complaintUser.getNickName());
        c.setComplaintUserHeadUrl(complaintUser.getAvatarUrl());

        c.setComplaintedUserNickName(complaintedUser.getNickName());
        c.setComplaintedUserHeadUrl(complaintedUser.getAvatarUrl());
        c.setComplaintTime(new Date());
        c.setCreatedTime(new Date());
        c.setId(null);
        mongoTemplate.insert(c);
        ComplaintUserStatistics complaintUserStatistics = new ComplaintUserStatistics();
        complaintUserStatistics.setUserId(c.getComplaintUserId());
        complaintUserStatistics.setComplaintedUserId(c.getComplaintedUserId());
        complaintUserStatistics.setComplaintTime(new Date());
        mongoTemplate.insert(complaintUserStatistics);
        log.info(":>>> 新增举报统计");

        return true;
    }

}
